package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JSONResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.security.Security;

public class MyFormFilter extends FormAuthenticationFilter{
    //限制登录成功或者失败的时候跳转页面,覆写只做信息提示
    /*


     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //登录成功时候
        //1.将json字符串响应到浏览器上
        response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult()));
        return false;
    }
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        //登录失败时
        //将异常信息打印出来: 供开发时方便
        //防止中文乱码
        response.setContentType("application/json;charset=UTF-8");
        e.printStackTrace();
        //创建通用异常提示信息
        String errorMsg = "其他异常信息,请联系管理员";
        //当异常信息是没有用户名的时候
        if (e instanceof UnknownAccountException) {
            errorMsg = "用户名不存在！";
        }
        //当异常信息是密码不匹配的时候
        if (e instanceof IncorrectCredentialsException) {
            errorMsg = "密码错误！";
        }
        try {
            //防止中文乱码
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(new ObjectMapper().writeValueAsString(new JSONResult().mark(errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return false;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
       //作用:避免重复登录之后无法进入
        //当挡墙访问的是login的时候进行登出操作
        if (isLoginRequest(request,response)) {
            //判断是否此时是否是登录的状态
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                subject.logout();
            }
        }
        //判断是否是已经登录的状态

        return super.isAccessAllowed(request, response, mappedValue);
    }
}
